package com.force.abril.transformer;

import java.util.Date;
import java.util.GregorianCalendar;

import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;

import org.aspectj.weaver.patterns.ParserException;

public class XMLGregorianCalendarTransformer {

	private DatatypeFactory df = null;
	
	private static XMLGregorianCalendarTransformer instance;
 
	private XMLGregorianCalendarTransformer() {
		try {

			df = DatatypeFactory.newInstance();

		} catch (DatatypeConfigurationException dce) {
			throw new IllegalStateException(
					"Exception while obtaining DatatypeFactory instance", dce);
		}

	}
	
	public synchronized static XMLGregorianCalendarTransformer getInstance() {
		if (instance == null) instance = new XMLGregorianCalendarTransformer();
		return instance;
	}

	/**
	 * Converts a java.util.Date into an instance of XMLGregorianCalendar
	 *
	 * @param date
	 *            Instance of java.util.Date or a null reference
	 * @return XMLGregorianCalendar instance whose value is based upon the value
	 *         in the date parameter. If the date parameter is null then this
	 *         method will simply return null.
	 */
	public XMLGregorianCalendar toXMLGregorianCalendar(Date date) {
		if (date == null)
			return null;
		GregorianCalendar gc = new GregorianCalendar();
		gc.setTimeInMillis(date.getTime());
		return df.newXMLGregorianCalendar(gc);
	}

	public Date toDate(XMLGregorianCalendar date) {
		if (date == null)
			return null;

		Date dateReturn = null;

		try {
			dateReturn = date.toGregorianCalendar().getTime();
		} catch (Exception e) {
			throw new ParserException("Parser operation failed.", null);
		}
		return dateReturn;
	}

}
